package com.rpc.provider.invoker;

import com.rpc.common.entity.request.RPCDTO;
import com.rpc.provider.invoker.handler.RPCInvokeHandler;
import com.rpc.provider.manager.RPCInvokeTargetManager;

import java.lang.reflect.Method;

public class RPCInvoker {
    private static RPCInvokeHandler handler = new RPCInvokeHandler();

    public static Object invoke(RPCDTO rpcdto) throws Throwable {
        Object[] args = rpcdto.getArgs();   //获取请求参数
        Class<?>[] types = new Class[args.length];
        for (int i = 0; i < args.length; ++i) {
            types[i] = args[i].getClass();  //设置参数类型
        }
        String interfaceName = rpcdto.getClassName();
        System.out.println(interfaceName);
        Object target = RPCInvokeTargetManager.getInvokeTarget(interfaceName);  //从调用对象管理器中找调用对象
        if (target == null) {
            throw new RuntimeException("找不到调用对象");
        }
        //反射调用
        Class targetClass = target.getClass();
        Method method = targetClass.getMethod(rpcdto.getMethodName(), types);
        return handler.invoke(target, method, args);
    }
}
